package com.jiang.jpa.service;

import cn.hutool.core.bean.BeanUtil;
import com.jiang.core.common.PageHelper;
import com.jiang.jpa.dao.UserRepository;
import com.jiang.jpa.entity.User;
import com.jiang.jpa.view.dto.UserDTO;
import com.jiang.jpa.view.dto.UserSearchDTO;
import com.jiang.jpa.view.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.awt.print.Book;
import java.util.List;


/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author jiang
 * @since 2022-10-27
 */
@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public void add(UserDTO DTO) {
        User user = new User();
        BeanUtil.copyProperties(DTO, user);
        userRepository.save(user);
    }

    public void del(Long id) {
        userRepository.deleteById(id);
    }

    public void update(Long id, UserDTO DTO) {
        User user = userRepository.getOne(id);
        BeanUtils.copyProperties(DTO, user);
        userRepository.save(user);
    }

    public UserVO getById(Long id) {
        User user = userRepository.getOne(id);
        UserVO vo = new UserVO();
        BeanUtil.copyProperties(user, vo);
        return vo;
    }

    public PageHelper<UserVO> page(UserSearchDTO DTO) {
        Pageable pageable = PageRequest.of(Integer.parseInt(DTO.getCurrentPage()+""), Integer.parseInt(DTO.getPageSize()+""), Sort.Direction.ASC, "id");
        Page<User> page = userRepository.findAll(new Specification<User>(){
            @Override
            public Predicate toPredicate(Root<User> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                return null;
            }
        },pageable);
        List<UserVO> userVOS = BeanUtil.copyToList(page.getContent(), UserVO.class);
        return new PageHelper<>(page.getNumber(), page.getTotalPages(), page.getSize(), userVOS);
    }
}
